package com.example.musicapp.service;

import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.example.musicapp.R;
import com.example.musicapp.bean.Music;
import com.example.musicapp.receiver.NotificationClickReceiver;
import com.example.musicapp.utils.CommonUtils;
import com.example.musicapp.view.IPlayViewControl;



import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.example.musicapp.utils.CommonUtils.judgeNum;
import static com.example.musicapp.utils.Constant.CLOSE;
import static com.example.musicapp.utils.Constant.NEXT;
import static com.example.musicapp.utils.Constant.NEXT_PLAY;
import static com.example.musicapp.utils.Constant.ORDER_PLAY;
import static com.example.musicapp.utils.Constant.PLAY;
import static com.example.musicapp.utils.Constant.PREV;
import static com.example.musicapp.utils.Constant.PRE_PLAY;
import static com.example.musicapp.utils.Constant.RANDOM_PLAY;
import static com.example.musicapp.utils.Constant.SINGLE_CYCLE_PLAY;

public class MediaService extends Service implements MediaPlayer.OnCompletionListener {

    private static final String TAG = "MediaService";
    private final MyBinder mBinder = new MyBinder();
    //标记当前歌曲的序号
    public static int sPlayPosition = 0;
    public static int PLAY_STATION = 0;


    //用以通知activity更新视图内容
    private List<Music> mMusicList = new ArrayList<>();


    private IPlayViewControl mViewController;
    private static RemoteViews remoteViews;
    private MusicReceiver musicReceiver;
    private static Notification sNotification;




    //初始化MediaPlayer
    private static volatile MediaPlayer sMediaPlayer;
    public MediaService() {


        if (sMediaPlayer == null) {
            synchronized (MediaService.class) {
                if (sMediaPlayer == null) {
                    sMediaPlayer =  new MediaPlayer();
                }
            }
        }
//        iniMediaPlayerFile(i);

    }


    /**
     * 初始化自定义通知栏 的按钮点击事件
     */
    private void initRemoteViews() {
        remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);

        //通知栏控制器上一首按钮广播操作
        Intent intentPrev = new Intent(PREV);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, intentPrev, 0);
        //为prev控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.ibtn_notification_last, prevPendingIntent);

        //通知栏控制器播放暂停按钮广播操作  //用于接收广播时过滤意图信息
        Intent intentPlay = new Intent(PLAY);
        PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, intentPlay, 0);
        //为play控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.ibtn_notification_play_pause, playPendingIntent);

        //通知栏控制器下一首按钮广播操作
        Intent intentNext = new Intent(NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intentNext, 0);
        //为next控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.ibtn_notification_next, nextPendingIntent);

        //通知栏控制器关闭按钮广播操作
        Intent intentClose = new Intent(CLOSE);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(this, 0, intentClose, 0);
        //为close控件注册事件
        remoteViews.setOnClickPendingIntent(R.id.ibtn_notification_close, closePendingIntent);

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mBinder.nextMusic();
    }

    /**
     * 广播接收器 （内部类）
     */
    public class MusicReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //UI控制
            UIControl(intent.getAction());
        }
    }

    /**
     * 页面的UI 控制 ，通过服务来控制页面和通知栏的UI
     *  @param state 状态码
     *
     */
    private void UIControl(String state) {
        switch (state) {
            case PLAY:
                mBinder.playMusic();

                break;
            case PREV:
                mBinder.preciousMusic();

                break;
            case NEXT:
                mBinder.nextMusic();

                break;
            case CLOSE:
                mBinder.closeNotification();
                stopForeground(true);

                break;
            default:
                break;
        }
    }

    /**
     * 注册动态广播
     */
    private void registerMusicReceiver() {
        musicReceiver = new MusicReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PLAY);
        intentFilter.addAction(PREV);
        intentFilter.addAction(NEXT);
        intentFilter.addAction(CLOSE);
        registerReceiver(musicReceiver, intentFilter);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initRemoteViews();
        //注册动态广播
        registerMusicReceiver();

        initNotification();
        sMediaPlayer.setOnCompletionListener(this);
//        showNotification();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (musicReceiver != null) {
            //解除动态注册的广播
            unregisterReceiver(musicReceiver);
        }
        stopForeground(true);

    }

    /**
     * 初始化通知
     */
    private void initNotification() {
        String channelId = "play_control";
        String channelName = "播放控制";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        createNotificationChannel(channelId, channelName, importance);

        //点击整个通知时发送广播
        Intent intent = new Intent(getApplicationContext(), NotificationClickReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //初始化通知
        sNotification = new NotificationCompat.Builder(this, "play_control")
                .setContentIntent(pendingIntent)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setCustomContentView(remoteViews)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setAutoCancel(false)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .build();
    }
    /**
     * 更改通知的信息和UI
     */
    public void updateNotificationShow() {
        //播放状态判断
        if (sMediaPlayer.isPlaying()) {
            remoteViews.setImageViewResource(R.id.ibtn_notification_play_pause, R.drawable.ic_baseline_pause_circle_filled_24);
        } else {
            remoteViews.setImageViewResource(R.id.ibtn_notification_play_pause, R.drawable.ic_baseline_play_circle_filled_24);
        }
        //封面专辑
//        remoteViews.setImageViewBitmap(R.id.iv_notification_music_album, ImageLoader.build(MyApp.getContext()).loadBitmap(mMusicList.get(i).getAlbum(),50,50));
        //歌曲名
        sPlayPosition= CommonUtils.judgeNum(sPlayPosition,mMusicList);
        remoteViews.setTextViewText(R.id.tv_notification_music_name, mMusicList.get(sPlayPosition).getSong());
        //歌手名
        remoteViews.setTextViewText(R.id.tv_notification_artist, mMusicList.get(sPlayPosition).getSinger());
        //发送通知
//        manager.notify(1, sNotification);
        startForeground(1,sNotification);
    }



    private static NotificationManager manager;



    /**
     * 创建通知渠道
     *
     * @param channelId   渠道id
     * @param channelName 渠道名称
     * @param importance  渠道重要性
     */
    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.enableLights(false);
        channel.enableVibration(false);
        channel.setVibrationPattern(new long[]{0});
        channel.setSound(null, null);
        //获取系统通知服务
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class MyBinder extends Binder {


        public void registerViewController(IPlayViewControl viewController) {
            mViewController = viewController;
        }


        private int mode;

        public void setMode(int mode) {
            this.mode = mode;
        }

        /**
         * 改变歌曲播放的状态
         * @param mode 播放模式
         * @param nextOrPre 下一首
         * @param position  上一首
         * @return 返回播放位置
         */
        private int changePlay(int mode,int nextOrPre,int position){
            if(mode == SINGLE_CYCLE_PLAY){

            }
            if (mode == RANDOM_PLAY){
                Random random = new Random();
                position = random.nextInt(mMusicList.size());
            }
            if(mode == ORDER_PLAY){
                if (nextOrPre == NEXT_PLAY){
                    position++;
                }
                if (nextOrPre == PRE_PLAY){
                    position--;
                }
            }
            return CommonUtils.judgeNum(position,mMusicList);
        }


        /**
         * 播放音乐
         */
        public void playMusic() {

            if (!sMediaPlayer.isPlaying()) {
                //如果还没开始播放，就开始
                sMediaPlayer.start();
                PLAY_STATION = 1;

            } else {
                sMediaPlayer.pause();
                PLAY_STATION = 0;
            }
            mViewController.onPlayerStateChange(PLAY_STATION);
            updateNotificationShow();
        }


        /**
         * 关闭音乐通知栏
         */
        public void closeNotification() {
            if (sMediaPlayer != null) {
                if (sMediaPlayer.isPlaying()) {
                    sMediaPlayer.pause();
                    PLAY_STATION = 0;
                }
            }
            mViewController.onPlayerStateChange(PLAY_STATION);
            manager.cancel(1);
        }


        /**
         * 下一首
         */
        public void nextMusic() {
            if (sMediaPlayer != null) {
                //切换歌曲reset()很重要很重要很重要，没有会报IllegalStateException
                sMediaPlayer.reset();
                sPlayPosition = changePlay(mode,NEXT_PLAY,sPlayPosition);
                iniMediaPlayerFile(sPlayPosition);


                playMusic();
            }
        }

        /**
         * 上一首
         */
        public void preciousMusic() {
            if (sMediaPlayer != null) {
                sMediaPlayer.reset();
                sPlayPosition = changePlay(mode,PRE_PLAY,sPlayPosition);




                iniMediaPlayerFile(sPlayPosition);


                playMusic();
            }
        }

        /**
         * 获取歌曲长度
         **/
        public int getProgress() {

            return sMediaPlayer.getDuration();
        }

        /**
         * 获取播放位置
         */
        public int getPlayPosition() {

            return sMediaPlayer.getCurrentPosition();
        }

        /**
         * 播放指定位置
         */
        public void seekToPositon(int mes) {
            sMediaPlayer.seekTo(mes);
        }


        public void setMusicList(List<Music> list, int position) {
            mMusicList = list;
            sPlayPosition = position;
            iniMediaPlayerFile(sPlayPosition);
        }
    }


    /**
     * 添加file文件到MediaPlayer对象并且准备播放音频
     */
    private void iniMediaPlayerFile(int dex) {
        //获取文件路径
        try {
            //此处的两个方法需要捕获IO异常
            //设置音频文件到MediaPlayer对象中
/*            if(sMediaPlayer.isPlaying()){
                sMediaPlayer.reset();
            }*/
//
//            if (i == dex){
//                return;
//            }
            sMediaPlayer.reset();

            dex = judgeNum(dex, mMusicList);
            sMediaPlayer.setDataSource(mMusicList.get(dex).getPath());
            //让MediaPlayer对象准备
            sMediaPlayer.prepare();
        } catch (IOException e) {
            Log.d(TAG, "设置资源，准备阶段出错");
            sMediaPlayer.reset();

            dex = judgeNum(dex, mMusicList);
            try {
                sMediaPlayer.setDataSource(mMusicList.get(dex).getPath());
                sMediaPlayer.prepare();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            //让MediaPlayer对象准备

            e.printStackTrace();
        }
    }




}